package com.doubleboy.flashlight;

import android.annotation.TargetApi;
import android.app.Activity;
import android.app.ActivityOptions;
import android.content.Intent;
import android.content.res.Configuration;
import android.graphics.drawable.TransitionDrawable;
import android.hardware.Camera;
import android.hardware.Camera.Parameters;
import android.os.Build;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewStub;
import android.widget.ImageSwitcher;
import android.widget.ImageView;
import android.widget.ViewSwitcher;

import com.doubleboy.flashlight.db.SaveInstance;
import com.doubleboy.flashlight.floatwindow.FloatWindowService;
import com.doubleboy.flashlight.lang.L;
import com.doubleboy.flashlight.view.SlideButton;

public class MainActivity extends Activity implements View.OnClickListener {

    private static boolean IS_CAMERA_OPEN = false;

	private Camera camera=null;
    private SaveInstance saveInstance = new SaveInstance();
    private View background;
    private SlideButton slideButton;
    private boolean isAutoOff = false;
    private boolean inIntroduce = false;
    /**
     * true:亮屏  false：暗屏
     */
    private boolean screenStatu;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        camera = MyApplication.getMyApplication().getCamera();
        slideButton = (SlideButton) findViewById(R.id.button);
        background = findViewById(R.id.background);
        screenStatu = saveInstance.getScreenStatus(this);
        if (screenStatu) {
            initLight();
		}
        slideButton.SetOnChangedListener(new SlideButton.OnChangedListener() {

            @Override
            public void OnChanged(boolean checkStatu) {
                flashLightSwitch(checkStatu);
                IS_CAMERA_OPEN = checkStatu;
                if (isAutoOff && !checkStatu) {
                    finish();
                }
            }
        });
        boolean isAutoOn = saveInstance.getAutoOn(this);
        if (isAutoOn) {
            slideButton.initStatu(true);
            slideButton.performChange();
        }
        initIntroduce();
    }

    @Override
    protected void onResume() {
        super.onResume();
        L.d("IS_CAMERA_OPEN:%b", IS_CAMERA_OPEN);
        slideButton.initStatu(IS_CAMERA_OPEN);
        isAutoOff = saveInstance.getAutoOff(this);
    }

    @Override
    protected void onRestoreInstanceState(Bundle savedInstanceState) {
        super.onRestoreInstanceState(savedInstanceState);
        L.i(null);
    }

    @Override
    public void onBackPressed() {
        super.onBackPressed();
        L.i("Camera is Open? %S", IS_CAMERA_OPEN);
        if (!IS_CAMERA_OPEN) {
            MyApplication.getMyApplication().exit();
        } else {
            moveTaskToBack(true);
        }
    }

    @Override
    public void onClick(View v) {
        //全屏操作
        if (v == background) {
            if (getActionBar().isShowing()) {

                getActionBar().hide();
            } else {
                getActionBar().show();
            }
        }
    }

    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
        L.i("newConfig:%S", newConfig.orientation);
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        L.i(null);
        saveInstance.setScreenStatu(this, screenStatu);
    }

    @Override
    protected void onDestroy() {
        L.i(null);
        saveInstance.setScreenStatu(this, screenStatu);
        super.onDestroy();
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.main, menu);
        return true;
    }

    @Override
    public boolean onPrepareOptionsMenu(Menu menu) {
        if (screenStatu) {
            menu.getItem(0).setIcon(R.drawable.screen_light);
        } else {
            menu.getItem(0).setIcon(R.drawable.screen_dark);
        }
        return super.onPrepareOptionsMenu(menu);
    }

    @TargetApi(Build.VERSION_CODES.JELLY_BEAN)
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        if (!inIntroduce) {
            switch (item.getItemId()) {
                case R.id.action_screen:
                    screenStatu = !screenStatu;
                    screenLight(screenStatu, 400);
                    invalidateOptionsMenu();
                    break;
                case R.id.action_settings:
                    L.i("action_settings");
                    Bundle translateBundle =
                            ActivityOptions.makeCustomAnimation(this,
                                    R.anim.slide_in_left, R.anim.slide_out_left).toBundle();
                    startActivity(new Intent(this, SettingActivity.class), translateBundle);
                    break;
            }
        }
        return super.onOptionsItemSelected(item);
    }

    /**
     * 初始化进入时候加上引导界面
     */
    private void initIntroduce() {
        boolean isFirst = saveInstance.isFirstOpen(this);
        if (isFirst) {
            ViewStub viewStub = (ViewStub) findViewById(R.id.introduce_sub);
            viewStub.inflate();
            ImageSwitcher imageSwitcher = (ImageSwitcher) findViewById(R.id.image_switcher);
            ImageSwitchFactory factory = new ImageSwitchFactory();
            imageSwitcher.setOnClickListener(factory);
            inIntroduce = true;
        }
    }

    /**
     * viewSwitch的工厂类
     */
    private class ImageSwitchFactory implements ViewSwitcher.ViewFactory, View.OnClickListener {

        private int time = 0;

        @Override
        public View makeView() {
            ImageView view = new ImageView(MainActivity.this);
            view.setScaleType(ImageView.ScaleType.CENTER_CROP);
            return view;
        }

        @Override
        public void onClick(View v) {
            L.d("times:%d", time);
            if (time > 0) {
                v.setVisibility(View.GONE);
                inIntroduce = false;
                return;
            }
            if (ImageSwitcher.class.isInstance(v)) {
                ImageSwitcher switcher = (ImageSwitcher) v;
                switcher.showNext();
                time++;
            }
        }
    }


    private void initLight() {
        TransitionDrawable transition = (TransitionDrawable) background.getBackground();
        transition.reverseTransition(1000);
    }

    private void screenLight(boolean screenStatu, int durationMillis) {
        TransitionDrawable transition = (TransitionDrawable) background.getBackground();
        transition.setCrossFadeEnabled(false);
        if (screenStatu) {
            transition.startTransition(durationMillis);
        } else {
            transition.reverseTransition(durationMillis);
        }
    }

    /**
     * 闪光灯开关
     *
     * @param isOpen
     * @return
     */
    private boolean flashLightSwitch(boolean isOpen) {
        try {
            Parameters params = camera.getParameters();
            if (isOpen) {
                params.setFlashMode(Parameters.FLASH_MODE_TORCH);
                camera.setParameters(params);
                camera.startPreview(); // 开始亮灯
                return true;
            } else {
                params.setFlashMode(Parameters.FLASH_MODE_OFF);
                camera.setParameters(params);
                camera.stopPreview(); // 关掉亮灯
                return false;
            }
        } catch (Exception e) {
			L.e(e.getMessage());
            return false;
        }
    }

    private void openFlashLightWindow(View view) {
        Intent intent = new Intent(MainActivity.this, FloatWindowService.class);
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        startService(intent);
        finish();
    }
}
